package cn.bdqn.service.sys.impl;


import cn.bdqn.dao.sys.SysRoleDao;
import cn.bdqn.dao.sys.SysUserDao;
import cn.bdqn.entity.SysUser;
import cn.bdqn.service.sys.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

import java.util.Map;

/**
 * @ProjectName: ycbdqn
 * @Package: cn.bdqn.service.sys.impl
 * @Author: huat
 * @Date: 2020/3/5 14:10
 * @Version: 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    SysUserDao sysUserDao;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    SysRoleDao sysRoleDao;

    /**
     * 根据用户名查询用户
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return sysUserDao.getUser(username);
    }
    /**
     * 将用户信息保存到session中
     * @param session
     * @return
     */

    @Override
    @Transactional
    public int updateSessionByUserId( HttpSession session) {

        //从security作用域中获取账号
        SysUser sysUser=sysUserDao.getUser(SecurityContextHolder.getContext().getAuthentication().getName());
        int result=sysUserDao.updateSessionByUserId(session.getId(),sysUser.getId());
        if(0<result){
            session.setAttribute("user",sysUser);

        }else{
            new RuntimeException("sessionID保存失败");
        }
        return result;
    }

    /**
     * 修改密码
     * @param oldPassword 原密码
     * @param password  新密码
     * @param id 用户id
     * @return
     */
    @Override
    @Transactional
    public int updatePasswordByUserId(String oldPassword, String password,int id) {
        String pwd=sysUserDao.getPasswordById(id);
        if(!passwordEncoder.matches(oldPassword,pwd)){
            return 0;
        }
        return sysUserDao.updatePasswordById(passwordEncoder.encode(password),id);

    }
    /**
     * 分页查询用户
     * @param page 起始位置
     * @param limit 页面大小
     * @param username 用户名
     * @return
     */
    @Override
    public Map<String, Object> getAllUser(int page, int limit, String username) {
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("count",sysUserDao.getCountUser(username));
        map.put("data",sysUserDao.sysUserList((page-1)*limit, limit, username));
        map.put("code","0");
        return map;
    }
    /**
     * 添加用户
     * @param sysUser 用户
     * @param roleId 用户角色id
     * @return
     */
    @Override
    @Transactional
    public int addUser(SysUser sysUser, String[] roleId) {
        SysUser result=sysUserDao.getUser(sysUser.getUsername());
        if(null!=result){
            return 2;
        }
        try{
            sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
            sysUserDao.addUser(sysUser);
            for (int i=0;i<roleId.length;i++){
                sysUserDao.addRoleByUser(sysUser.getId(),Integer.parseInt(roleId[i]));
            }

        }catch (Exception e){
            e.printStackTrace();
            return 3;
        }
        return 1;
    }

    /**
     * 根据id查询用户
     * @param id 用户id
     * @return 用户对象
     */
    @Override
    public SysUser getSysUser(int id){
        return sysUserDao.getSysUser(id);
    }
    /**
     * 修改用户信息
     * @param sysUser 用户对象
     * @param roleId    角色id
     * @return
     */
    @Transactional
    @Override
    public boolean updateUserByAdmin(SysUser sysUser, String[] roleId) {
      try{
          sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
          sysUserDao.updatePasswordById(sysUser.getPassword(),sysUser.getId());
          sysRoleDao.delRoleByUserId(sysUser.getId());
          for (int i=0;i<roleId.length;i++){
              sysUserDao.addRoleByUser(sysUser.getId(),Integer.parseInt(roleId[i]));
          }
      }catch (Exception e){
        return false;
      }
      return true;
    }
    /**
     * 通过id删除用户
     * @param id
     * @return
     */
    @Override
    @Transactional
    public boolean deleteUserById(int id) {
        int result=-1;
       try {
           result=sysUserDao.deleteUserById(id);
           result=sysRoleDao.delRoleByUserId(id);
       }catch (Exception e){
           e.printStackTrace();
           return false;
       }
       return result>=0?true:false;
    }
}
